﻿using System;
using System.Data;
using System.Drawing;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dundas.Charting.WebControl;
using LenderClearingHouse.Helpers;
using Microsoft.SqlServer.Server;

namespace LenderClearingHouse
{
    public partial class Dashboard3 : PageBase
    {
        private const int StartRowIndex = 0;
        private const int pageSize = 5;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            var listDate = DateValidator.ValidateCalendarDate(txtFromDate.Text, txtToDate.Text, CalendarFromDate.SelectedDate, CalendarToDate.SelectedDate);
            txtFromDate.Text = listDate.ElementAt(0).ToString();
            txtToDate.Text = listDate.ElementAt(1).ToString();
            CalendarFromDate.SelectedDate = Convert.ToDateTime(listDate.ElementAt(2));
            CalendarToDate.SelectedDate = Convert.ToDateTime(listDate.ElementAt(3));

            pagerBottom.Visible = true;
            pagerTop.Visible = true;
            pagerTop.PageSize = pageSize;
            pagerBottom.PageSize = pageSize;

            for (int i = 0; i <= 4; ++i)
            {
                Chart1.Series[i].Type = SeriesChartType.Line;
                Chart1.Series[i].MarkerStyle = MarkerStyle.Square;
                Chart1.Series[i].MarkerSize = 10;
                Chart1.Series[i].EmptyPointStyle.BorderWidth = 0;
                Chart1.Series[i].EmptyPointStyle.MarkerStyle = MarkerStyle.None;
                Chart1.Series[i]["LabelStyle"] = "Right";
                Chart1.Series[i].Points.Clear();
            }

            Chart1.ChartAreas[0].AxisX.Interval = 1;
            Chart1.ChartAreas[0].AxisX.LabelStyle.ShowEndLabels = false;
            Chart1.ChartAreas[0].AxisY.Title = "$ (Dollars)";
            Chart1.ChartAreas[0].AxisY.TitleFont = new Font("Microsoft Sans Serif", 15);

            //Chart1.Legends[0].Position.Auto = false;
            //Chart1.Legends[0].Position = new ElementPosition(30, 5, 100, 20);
            
            Chart1.Legends.Add(new Legend("Legend2"));
            Chart1.Legends[1].Position.Auto = false;
            Chart1.Legends[1].Position.X = 79;
            Chart1.Legends[1].Position.Y = 45;
            Chart1.Legends[1].Position.Height = 10;
            Chart1.Legends[1].Position.Width = 20;
            Chart1.Series[4].Legend = "Legend2";

            if (!this.Page.IsPostBack)
            {
                // Set initial X axis zooming
                //this.Chart1.ChartAreas["Default"].AxisX.View.Position = -1;
                //this.Chart1.ChartAreas["Default"].AxisX.View.Size = 7.5;

                FillChart(0);

                cbInvestor.Visible = lbIvestor.Visible; 
            }
        }

        private void FillChart(int startRow)
        {
            User u = Session["User"] as User;
            DateTime fromDate = CalendarFromDate.SelectedDate.HasValue ? CalendarFromDate.SelectedDate.Value : DateTime.Now;
            DateTime toDate = CalendarToDate.SelectedDate.HasValue?CalendarToDate.SelectedDate.Value:DateTime.Now;  

            int investorId = -1;
            if (u.UserRole == UserRole.SuperAdmin)
            {
                investorId = cbInvestor.SelectedIndex != -1 ? int.Parse(cbInvestor.SelectedValue) : -1;
            }
            else
            {
                investorId = int.Parse(u.UserId);
            }

           

            DataAccess da = new DataAccess();
            DataTable tbl;

            if ((u.UserRole == UserRole.InvestorUser) || (u.UserRole == UserRole.InvestorAdmin))
                tbl = da.GetDataTable("getDashboard3", new string[] { "@InvestorId", "@fromDate", "@toDate" }, new object[] { u.UserId, fromDate, toDate });  
            else if (u.UserRole == UserRole.SuperAdmin)
            {
                tbl = investorId > 0 ? da.GetDataTable("getDashboard3", new string[] { "@InvestorId", "@fromDate", "@toDate" }, new object[] { investorId, fromDate, toDate })
                    : da.GetDataTable("getDashboard3", new string[] { "@fromDate", "@toDate" }, new object[] { fromDate, toDate }); 
            }
                
            else
            {
                SetNoAccess();
                return;
            }
            
            for (int i = 0; i <= 3; ++i)
                Chart1.Series[i].Points.Clear();
            
            System.Globalization.DateTimeFormatInfo fi = new System.Globalization.DateTimeFormatInfo();
            for (int i = startRow; i < Math.Min(startRow + pageSize, tbl.Rows.Count); ++i)
            {
                DataRow dr = tbl.Rows[i];
                int j = i - startRow;
                string strMonthName = fi.GetAbbreviatedMonthName(Convert.ToInt32(dr["IdSub"])).ToString();

                if (dr.IsNull("AvgSellingPrice"))
                    Chart1.Series[0].Points.AddXY(j, double.NaN);
                else
                {
                    Chart1.Series[0].Points.AddXY(j, Convert.ToInt32(dr["AvgSellingPrice"]));
                    Chart1.Series[0].Points[j].Label = dr["AvgSellingPriceProc"].ToString() + "%";
                }
                if (dr.IsNull("AvgPurchasePrice"))
                    Chart1.Series[1].Points.AddXY(j, double.NaN);
                else
                {
                    Chart1.Series[1].Points.AddXY(j, Convert.ToInt32(dr["AvgPurchasePrice"]));
                    Chart1.Series[1].Points[j].Label = dr["AvgPurchasePriceProc"].ToString() + "%";
                }
                if (dr.IsNull("AvgRehabCosts"))
                    Chart1.Series[2].Points.AddXY(j, double.NaN);
                else
                {
                    Chart1.Series[2].Points.AddXY(j, Convert.ToInt32(dr["AvgRehabCosts"]));
                    Chart1.Series[2].Points[j].Label = dr["AvgRehabCostsProc"].ToString() + "%";
                }
                if (dr.IsNull("AvgRehabCosts"))
                    Chart1.Series[3].Points.AddXY(j, double.NaN);
                else
                {
                    Chart1.Series[3].Points.AddXY(j, Convert.ToInt32(dr["AvgNetProfit"]));
                    Chart1.Series[3].Points[j].Label = dr["AvgNetProfitProc"].ToString() + "%";
                }
                if (dr.IsNull("AvgPurchasePlusCostOperation"))
                    Chart1.Series[4].Points.AddXY(j, double.NaN);
                else
                {
                    Chart1.Series[4].Points.AddXY(j, Convert.ToInt32(dr["AvgPurchasePlusCostOperation"]));
                    Chart1.Series[4].Points[j].Label = "100%";
                }
                                   
                Chart1.Series[0].Points[j].AxisLabel = strMonthName + " " + dr["IdYear"].ToString();
                Chart1.Series[1].Points[j].AxisLabel = strMonthName + " " + dr["IdYear"].ToString();
                Chart1.Series[2].Points[j].AxisLabel = strMonthName + " " + dr["IdYear"].ToString();
                Chart1.Series[3].Points[j].AxisLabel = strMonthName + " " + dr["IdYear"].ToString();
            }

            if (tbl.Rows.Count < 1)
            {
                pagerBottom.Visible = false;
                pagerTop.Visible = false;
            }

            lvFake.DataSource = tbl;
            lvFake.DataBind();
        }

        protected void lvFake_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        {
            pagerBottom.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
            pagerTop.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

            FillChart(e.StartRowIndex);
        }

        private void SetNoAccess()
        {
            Chart1.Visible = false;
            pagerBottom.Visible = false;
            pagerTop.Visible = false;
        }

        protected void cbInvestor_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            pagerBottom.SetPageProperties(StartRowIndex, pageSize, false);
            pagerTop.SetPageProperties(StartRowIndex, pageSize, false);
            FillChart(StartRowIndex);
        }

        protected void calendarDate_Changed(object sender, System.EventArgs e)
        {
            pagerBottom.SetPageProperties(StartRowIndex, pageSize, false);
            pagerTop.SetPageProperties(StartRowIndex, pageSize, false);
            lblDataValidate.Style.Add("display", "none");
            FillChart(StartRowIndex);
        }       
    }
}